package com.polaris.live.utils

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.polaris.live.common.util.StructUtils

/**
 * TaskRedProxy
 * @author Created by 天晴 on 2024/10/30 15:53
 * @since 1.0.0
 **/
object TaskRedProxy {

    private var haveRed = false
    private val listeners = StructUtils.newSaleSet<TaskRedListener>()

    fun observe(owner: LifecycleOwner, observer: TaskRedListener) {
        listeners.add(observer)

        listeners.add(observer)
        owner.lifecycle.addObserver(object : LifecycleEventObserver {
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                if (event == Lifecycle.Event.ON_DESTROY) {
                    listeners.remove(observer)
                    owner.lifecycle.removeObserver(this)
                }
            }
        })
    }

    fun update(isRed: Boolean) {
        if (haveRed == isRed) return
        haveRed = isRed
        listeners.forEach { it.updateRed(isRed) }
    }

    fun isRedAvailable(): Boolean = haveRed
}

interface TaskRedListener {
    fun updateRed(isRed: Boolean)
}